package cz.possoft.serializable.clovece.cube;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Implementation based on reading next value on cube from stdin.
 * 
 * @author <a href="mailto:mposolda@gmail.com">Marek Posolda</a>
 */
public class StdinCubeGenerator implements CubeGenerator
{
   private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

   /**
    * {@inheritDoc}
    */
   public int nextValue()
   {
      int result = 0;
      
      while (result == 0)
      {
         String str = null;      
         try
         {
            System.out.print("Number for next playing with dice: ");
            str = reader.readLine();
            result = Integer.parseInt(str.trim()); 
            
            // better for testing (we can add more stdin values thanks to this)
            if ((result < 1) || (result > 6))
            {
               result = 6;
            }
         }
         catch (IOException ioe)
         {
            throw new RuntimeException(ioe);
         }
         catch (NumberFormatException nfe)
         {
            System.err.println(str + " is not valid number! Try again.");
            result = 0;
         }
      }
      
      return result;
   }

}

